<template>
  <div>
    <el-dialog
      v-model="centerDialogVisible"
      title="新建用户"
      width="30%"
      center
      destroy-on-close
    >
      <!--content-->

      <dd-form v-bind="modalFormConfig" v-model="formData"></dd-form>
      <slot></slot>
      <!--      footer-->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmClick">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, defineProps, defineExpose, watch } from 'vue'
import DdForm from '@/base-ui/form'
import { useStore } from 'vuex'

const props = defineProps({
  modalFormConfig: {
    type: Object,
    required: true
  },
  defaultInfo: {
    type: Object,
    default: () => ({})
  },
  pageName: {
    type: String,
    required: true
  },
  otherInfo: {
    type: Object,
    default: () => ({})
  }
})

const formItems = props.modalFormConfig?.formItems ?? []
const formData = ref({})
watch(
  () => props.defaultInfo,
  (newValue) => {
    for (const item of formItems) {
      formData.value[item.field] = newValue[item.field]
    }
  },
  {
    immediate: true,
    deep: true
  }
)

const centerDialogVisible = ref(false)
const changeDialogVisible = () => {
  centerDialogVisible.value = true
}
defineExpose({
  changeDialogVisible
})

//确认提交逻辑，包括新增和编辑
const store = useStore()
const handleConfirmClick = () => {
  //根据有无密码项，即defaultInfo来判断
  if (Object.keys(props.defaultInfo).length) {
    //编辑,发送网络请求  /user/id 带body--editData
    store.dispatch('system/updatePageDataAction', {
      pageName: props.pageName,
      editData: { ...formData.value, ...props.otherInfo },
      id: props.defaultInfo.id
    })
  } else {
    //新增，发送post网络请求  /user  带body--newData
    store.dispatch('system/createPageDataAction', {
      pageName: props.pageName,
      newData: { ...formData.value, ...props.otherInfo }
    })
  }

  centerDialogVisible.value = false
}
</script>

<style scoped></style>
